package com.example.test.advice.第九章_多线程和并发.建议131_CyclicBarrier让多线程齐步走;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;

//栅栏:让多线程齐步走
public class Client {

    public static void main(String[] args) {
        //设置汇集数量，以及会合后完成的任务
        CyclicBarrier cb = new CyclicBarrier(2, () -> System.out.println("隧道已经打通"));

        //工人1挖隧道
        new Thread(new Worker(cb),"工人1").start();
        //工人2挖隧道
        new Thread(new Worker(cb),"工人2").start();
    }

    static class Worker implements Runnable{

        private CyclicBarrier cb;

        public Worker(CyclicBarrier cb) {
            this.cb = cb;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(new Random().nextInt(1000));
                System.out.println(Thread.currentThread().getName()+"-到达汇合点。");
                //到达汇合点
                cb.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
